<template>
	<div class="login-container">
		<div class="left_space" />
		<div class="login_img">
			<img src="@/assets/images/login_img.png">
		</div>
		<div class="center_space" />
		<div class="form_box">
			<el-form ref="loginForm" :model="loginForm" class="login-form" autocomplete="on" label-position="left">
				<!-- <div class="title-container">
          <img src="@/assets/images/login_logo.png" alt>
          <div class="title">{{ title }}</div>
        </div> -->
				<el-form-item prop="username">
					<!-- <div class="before_input">用户名:</div> -->
					<el-input ref="username" v-model="loginForm.username"
						:placeholder="$t('placeholderTip.enter') + $t('placeholderTip.accountNumber')" name="username" type="text"
						tabindex="1" autocomplete="off" maxlength="12" @keyup.enter.native="handleLogin" />
				</el-form-item>

				<el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
					<el-form-item prop="password">
						<!-- <div class="before_input">密码:</div> -->
						<el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
							:placeholder="$t('placeholderTip.enter') + $t('placeholderTip.password')" name="password" tabindex="2"
							autocomplete="off" @keyup.native="checkCapslock" @blur="capsTooltip = false"
							@keyup.enter.native="handleLogin" />
						<!-- <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span> -->
					</el-form-item>
				</el-tooltip>

				<el-form-item class="code_box" prop="code">
					<el-input ref="verificationCode" v-model="loginForm.code"
						:placeholder="$t('placeholderTip.enter') + $t('placeholderTip.verificationCode')" name="verificationCode"
						type="text" tabindex="3" autocomplete="off" style="width: calc(100% - 120px);margin-right: 5px;"
						@keyup.enter.native="handleLogin" />
					<el-image class="codeId" :src="codeIdImg" style="width: 110px; height: 40px;" @click.stop="changeKanptcha">
						<div slot="error" class="image-slot" @click.stop="changeKanptcha">
							<i class="el-icon-picture-outline" />{{ $t('tag.refresh') }}
						</div>
					</el-image>
				</el-form-item>

				<!-- <div style="text-align: right;">
          <el-checkbox v-model="rember" style="color: #29b5ff" tabindex="4">记住密码</el-checkbox>
        </div> -->

				<el-button :loading="loading" type="primary"
					style="width: 100%;margin-top: 14px;line-height: 24px;font-size: 18px;font-weight: 400;" tabindex="5"
					@click.native.prevent="handleLogin">{{ $t('tag.logon') }}</el-button>

				<!-- <div style="position:relative">
        <div class="tips">
          <span>Username : admin</span>
          <span>Password : any</span>
        </div>
        <div class="tips">
          <span style="margin-right:18px;">Username : editor</span>
          <span>Password : any</span>
        </div>

        <el-button class="thirdparty-button" type="primary" @click="showDialog=true">
          Or connect with
        </el-button>
        </div>-->
			</el-form>
		</div>
		<div class="right_space">
			<Lang class="right-menu-item" style="position: absolute;top: 30px;right: 30px;font-size:24px"></Lang>
		</div>
		<!-- 语言包 -->

	</div>
</template>

<script>
// import { validUsername, validPassword } from '@/utils/validate'
// import SocialSign from './components/SocialSignin'
import defaultSettings from '@/settings.js';
export default {
	name: 'Login',
	// components: { SocialSign },
	data() {
		// const validateUsername = (rule, value, callback) => {
		//   if (!validUsername(value)) {
		//     callback(new Error('请输入正确的用户名'))
		//   } else {
		//     callback()
		//   }
		// }
		// const validatePassword = (rule, value, callback) => {
		//   var code = validPassword(value);
		//   if (code === 0) {
		//     callback()
		//   } else if (code === -1) {
		//     callback(new Error('密码不能为空!'))
		//   } else if (code === 1) {
		//     callback(new Error('密码必须以字母开头!'))
		//   } else if (code === 2) {
		//     callback(new Error('密码长度为6~16!'))
		//   } else if (code === 3) {
		//     callback(new Error('密码必须同时包含字母和数字!'))
		//   }
		// }
		return {
			canvas: null,
			baseUrl: defaultSettings.BASE_RUL,
			codeIdImg: null,
			title: defaultSettings.title,
			rember: false,
			loginForm: {
				username: '',
				password: '',
				code: '',
				codeId: ''
			},
			passwordType: 'password',
			capsTooltip: false,
			loading: false,
			showDialog: false,
			redirect: undefined,
			otherQuery: {},
			centerX: '',
			centerY: ''
		};
	},
	computed: {

	},
	watch: {
		$route: {
			handler: function (route) {
				const query = route.query;
				if (query) {
					this.redirect = query.redirect;
					this.otherQuery = this.getOtherQuery(query);
				}
			},
			immediate: true
		}
	},
	created() {
		window._vm = this;
		this.changeKanptcha();
		// window.addEventListener('storage', this.afterQRScan)
	},
	mounted() {
		this.getRemberAccount();
		if (this.loginForm.username === '') {
			this.$refs.username.focus();
		} else if (this.loginForm.password === '') {
			this.$refs.password.focus();
		} else if (this.loginForm.code === '') {
			this.$refs.verificationCode.focus();
		}
	},
	destroyed() {
		// window.removeEventListener('storage', this.afterQRScan)
	},
	methods: {
		refreshCanvas() {
			// try {
			//   setTimeout(() => {
			//     var view = document.getElementsByTagName('canvas')[0];
			//     view.style.width = window.innerWidth;
			//     view.style.height = window.innerHeight;
			//   }, 100);
			// } catch (error) {
			//   //
			// }
		},
		getRemberAccount() {
			// console.log('getRemberAccount');
			var rember = localStorage.getItem('erp_rember');
			if (rember) {
				this.rember = true;
				var accountList = localStorage.getItem(rember);
				if (accountList) {
					accountList = JSON.parse(accountList);
					var account = accountList[0];
					this.loginForm.username = account.username;
					this.loginForm.password = account.password;
				}
			} else {
				this.rember = false;
			}
		},
		saveAccount() {
			// console.log('saveAccount');
			var key = localStorage.getItem('erp_rember'),
				accountList = [];
			if (this.rember) {
				if (key) {
					accountList = localStorage.getItem(key);
					if (accountList) {
						accountList = JSON.parse(accountList);
					}
				} else {
					key = new Date('erp_' + new Date());
					localStorage.setItem('erp_rember', key);
				}
				if (accountList.length) {
					var index = accountList.find(
						(item) => item.username === this.loginForm.username
					);
					if (index >= 0) {
						accountList.splice(index, 1);
					}
					accountList.unshift({
						username: this.loginForm.username,
						password: this.loginForm.password
					});
					localStorage.setItem(key, JSON.stringify(accountList));
				} else {
					accountList.push({
						username: this.loginForm.username,
						password: this.loginForm.password
					});
					localStorage.setItem(key, JSON.stringify(accountList));
				}
			} else {
				if (key) {
					localStorage.removeItem(key);
				}
				localStorage.removeItem('erp_rember');
			}
		},
		changeKanptcha() {
			this.loginForm.code = '';
			this.getGuid();
			if (this.loginForm.codeId) {
				this.codeIdImg =
					this.baseUrl +
					'auth/checkCode?codeId=' +
					this.loginForm.codeId;
			}
		},
		getGuid() {
			var d = new Date().getTime();
			if (window.performance && typeof window.performance.now === 'function') {
				d += performance.now();
			}
			var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
				/[xy]/g,
				(c) => {
					var r = (d + Math.random() * 16) % 16 | 0;
					d = Math.floor(d / 16);
					return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
				}
			);
			this.loginForm.codeId = uuid;
		},
		checkCapslock(e) {
			const { key } = e;
			this.capsTooltip = key && key.length === 1 && key >= 'A' && key <= 'Z';
		},
		showPwd() {
			if (this.passwordType === 'password') {
				this.passwordType = '';
			} else {
				this.passwordType = 'password';
			}
			this.$nextTick(() => {
				this.$refs.password.focus();
			});
		},
		handleLogin() {
			if (this.checkLoginInfo()) {
				this.$refs.loginForm.validate((valid) => {
					if (valid) {
						this.loading = true;
						this.$store
							.dispatch('user/login', this.loginForm)
							.then(() => {
								this.saveAccount();
								this.$router.push({
									path: this.redirect || '/',
									query: this.otherQuery
								});
								this.loading = false;
							})
							.catch(() => {
								this.loading = false;
								this.changeKanptcha();
							});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		checkLoginInfo() {
			var flag = false,
				msg = '';
			if (this.loginForm) {
				if (!this.loginForm.username) {
					msg = this.$t('placeholderTip.accountNumber');
				} else if (!this.loginForm.password) {
					msg = this.$t('placeholderTip.password');
				} else if (!this.loginForm.code) {
					msg = this.$t('placeholderTip.verificationCode');
				} else {
					flag = true;
				}
			} else {
				this.$router.go(0);
			}
			if (!flag) {
				this.$message({ message: msg + this.$t('placeholderTip.noEmpty'), type: 'error' });
			}
			return flag;
		},
		getOtherQuery(query) {
			return Object.keys(query).reduce((acc, cur) => {
				if (cur !== 'redirect') {
					acc[cur] = query[cur];
				}
				return acc;
			}, {});
		}
		// afterQRScan() {
		//   if (e.key === 'x-admin-oauth-code') {
		//     const code = getQueryObject(e.newValue)
		//     const codeMap = {
		//       wechat: 'code',
		//       tencent: 'code'
		//     }
		//     const type = codeMap[this.auth_type]
		//     const codeName = code[type]
		//     if (codeName) {
		//       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
		//         this.$router.push({ path: this.redirect || '/' })
		//       })
		//     } else {
		//       alert('第三方登录失败')
		//     }
		//   }
		// }
	}
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
@import url('./bg_starfield.scss');
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
	.login-container .el-input input {
		color: $cursor;
	}
}

input:-webkit-autofill,
input:-internal-autofill-selected {
	background-color: transparent !important;
	border: 0px;
	-webkit-appearance: none;
	border-radius: 0px;
	padding: 12px 5px 12px 15px;
	color: #46a6ff;
	font-size: 14px;
	height: 41px;
	caret-color: $cursor;
	box-shadow: inset 0 0 0 1000px #f3f3f3 !important;
}

input:-internal-autofill-previewed,
input:-internal-autofill-selected {
	-webkit-text-fill-color: #46a6ff !important;
	box-shadow: 0 0 0px 1000px #435060 inset !important;
}

/* reset element-ui css */
.login-container {
	position: relative;

	.before_input {
		font-size: 16px;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #333333;
		display: inline-block;
		width: 4em;
	}

	.el-form-item__content {
		// display: flex;
		// justify-content: center;
		// align-items:center;
	}

	.el-input {
		display: inline-block;
		height: 41px;
		border: 1px solid #d9d9d9;
		background-color: #232323;
		border-radius: 5px;
		overflow: hidden;

		input {
			background: transparent;
			border: 0px;
			-webkit-appearance: none;
			border-radius: 0px;
			padding: 12px 5px 12px 15px;
			color: #DFB771;
			font-size: 14px;
			height: 41px;
			caret-color: $cursor;

			&::placeholder {
				color: #b2b2b2;
			}
		}
	}

	.code_box>div {
		display: flex;
		align-items: center;
	}

	input:-webkit-autofill,
	input:-internal-autofill-selected {
		background-color: transparent !important;
		border: 0px;
		-webkit-appearance: none;
		border-radius: 0px;
		padding: 12px 5px 12px 15px;
		color: #46a6ff;
		font-size: 14px;
		height: 41px;
		caret-color: $cursor;
	}

	.image-slot {
		width: 110px;
		height: 40px;
		background-color: #fff;
		text-align: center;
		color: #46a6ff;
		cursor: pointer;
	}
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
	position: relative;
	min-height: 720px;
	height: 100%;
	width: 100%;
	background-color: #232323;
	overflow: hidden;
	display: flex;
	flex-direction: row;
	justify-content: flex-start;

	canvas {
		position: absolute;
		z-index: 1;
	}

	@media screen and (min-width: 1920px) {
		.form_box {
			flex: 5 5 0;
			max-width: 450px;

			&>form {
				// width: 100%;
				width: 90%;
			}
		}

		.left_space,
		.right_space {
			flex: 4 4 0;
			width: 100%;
			position: relative;
		}

		::v-deep .international-icon {
			font-size: 24px;
		}

		.center_space {
			flex: 1 1 0;
			max-width: 240px;
		}

		.login_img {
			flex: 10 10 0;
			max-width: 100%;

			img {
				width: 700px !important;
			}
		}
	}

	@media screen and (max-width: 960px) {
		&>div.login_img {
			display: none !important;
		}

		&>div.center_space {
			display: none !important;
		}
	}

	.left_space,
	.right_space {
		flex: 1 1 0;
		width: 100%;
	}

	.center_space {
		flex: 1 1 0;
	}

	.login_img {
		flex: 10 10 0;
		width: 100%;

		img {
			width: 600px;
		}
	}

	&>div {
		z-index: 2;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100%;

		&.left {
			flex: 2 2 0;
			width: 100%;
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;
			height: 100%;
		}
	}

	.login-form {
		flex: 0 0 auto;
		width: 400px;
		// height: 422px;
		// background-color: #29b5ff16;
		border-radius: 10px;
		box-sizing: border-box;
		padding: 0 30px;

		.title-container {
			display: flex;
			justify-content: space-evenly;
			align-items: center;
			height: 88px;
			// border-bottom: 1px solid #D8B581;
			margin-bottom: 22px;

			img {
				width: 74px;
				height: 38px;
			}

			.title {
				font-size: 24px;
				font-family: Microsoft YaHei;
				font-weight: bold;
				color: #ffffff;
			}
		}
	}

	.tips {
		font-size: 14px;
		color: #fff;
		margin-bottom: 10px;

		span {
			&:first-of-type {
				margin-right: 16px;
			}
		}
	}

	.svg-container {
		padding: 6px 5px 6px 15px;
		color: $dark_gray;
		vertical-align: middle;
		width: 30px;
		display: inline-block;
	}

	.show-pwd {
		position: absolute;
		right: 10px;
		top: 7px;
		font-size: 16px;
		color: $dark_gray;
		cursor: pointer;
		user-select: none;
	}

	.thirdparty-button {
		position: absolute;
		right: 0;
		bottom: 6px;
	}

	@media only screen and (max-width: 470px) {
		.thirdparty-button {
			display: none;
		}
	}
}
</style>
